package cn.stacey.day13;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Client2fx extends Application{
	//持续发送消息
	private DataOutputStream out;
	private Socket socket;

	@Override
	public void start(Stage primaryStage) throws Exception {
		// TODO Auto-generated method stub
		VBox box=new VBox(10);
		//box距离上右下左10px
		box.setPadding(new Insets(10));
		
		//多行输入
		TextArea ta=new TextArea();
		//多行输入占据垂直方向
		VBox.setVgrow(ta, Priority.ALWAYS);
		//单行输入
		TextField tf=new TextField();
		box.getChildren().addAll(ta,tf);
		
		//监听回车事件
		tf.setOnKeyPressed((event)->{
			KeyCode code=event.getCode();
			if(code==KeyCode.ENTER) {
				String message=tf.getText();
				if("".equals(message)) {
					return;
				}
				ta.appendText(message+"\n");
				tf.setText("");
				if("886".equals(message)) {
					UtilsClose.closeQuitely(out);
					UtilsClose.closeQuitely(socket);
					//正常退出程序System.exit(0);
					System.exit(0);
				}
				
						try {
							out.writeUTF(message);
							//强刷进去
							out.flush();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

			}
		});
		Scene scene=new Scene(box,400,300);
		primaryStage.setScene(scene);
		primaryStage.show();
		openSocket();
		
	}
	
	public void openSocket() {
		try {
			socket=new Socket("127.0.0.1",6666);
//			OutputStream out=socket.getOutputStream();理解这句话
			out=new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
			InputStream in=System.in;
//			BufferedReader bf=new BufferedReader(new InputStreamReader(in,"utf-8"));
//			String line=bf.readLine();

			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void stop() throws Exception {
		// TODO Auto-generated method stub
		super.stop();
		UtilsClose.closeQuitely(out);
		UtilsClose.closeQuitely(socket);
		
	}
	public static void main(String[] args) {
		launch(args);
	}
}
